package summary;

import java.util.ArrayList;
import java.util.Collections;
import java.util.LinkedList;
import java.util.List;

/**
 * @Author: 海琳琦
 * @Date: 2022/3/13 15:23
 * https://leetcode-cn.com/problems/binary-tree-level-order-traversal-ii/
 */
public class Title107 {

    class TreeNode {
        int val;
        TreeNode left;
        TreeNode right;

        public TreeNode() {
        }

        public TreeNode(int val) {
            this.val = val;
        }

        public TreeNode(int val, TreeNode left, TreeNode right) {
            this.val = val;
            this.left = left;
            this.right = right;
        }
    }

    public List<List<Integer>> levelOrderBottom(TreeNode root) {
        List<List<Integer>> result = new ArrayList<>();
        if (root == null) {
            return result;
        }
        LinkedList<TreeNode> list = new LinkedList<>();
        list.offer(root);
        while (!list.isEmpty()) {
            int size = list.size();
            List<Integer> levelValue = new ArrayList<>();
            while (size-- > 0) {
                TreeNode node = list.poll();
                levelValue.add(node.val);
                if (node.left != null) {
                    list.offer(node.left);
                }
                if (node.right != null) {
                    list.offer(node.right);
                }
            }
            result.add(levelValue);
        }
        Collections.reverse(result);
        return result;
    }




    public List<List<Integer>> levelOrderBottom1(TreeNode root) {
        List<List<Integer>> result = new ArrayList<>();
        dfs(root, result, 0);
        Collections.reverse(result);
        return result;
    }

    private void dfs(TreeNode root, List<List<Integer>> result, int depth) {
        if (root == null) {
            return;
        }
        depth++;
        if (result.size() < depth) {
            List<Integer> temp = new ArrayList<>();
            result.add(temp);
        }
        result.get(depth - 1).add(root.val);
        dfs(root.left, result, depth);
        dfs(root.right, result, depth);
    }


    public static void main(String[] args) {

    }
}
